<template>
  <!-- 新闻推荐组件 -->
  <div class="user-articles">
    <van-pull-refresh 
    v-model="refreshing" 
    @refresh="onRefresh"
    :success-text="dropDownRefresh"
    success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >

        <articleItem 
        v-for="(articleList, index) in list"
        :key="index"
        :articleList="articleList"
        />

      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import {getPushArticles} from '@/service/getDate'
import articleItem from '@/page/home/children/children/articles-item.vue'
export default {
  name: 'articlesPiece',
  data() {
    return {
      list: [],
      loading: false,
      finished: false, // 检测数据是否全部加载完毕
      refreshing: false,
      error: false, // 当用户点击错误提示时  error变为true 继续加载数据
      timesTamp: null, // 请求数据的时间戳
      dropDownRefresh: '', // 下拉加载时显示的提示文本
    };
  },
  props: {
    // 当前点击的频道
    channel: {
      type: Object,
      required: true
    } 
  },
  created () {
  },
  components:{
    articleItem
  },
  methods: {
  // 下拉刷新
   async onLoad() {
      try {
        const {data} = await getPushArticles({
          channel_id: this.channel.id,
          timestamp: this.timesTamp || Date.now()
        })

        const {results} = data.data
        this.list.push(...results)
        console.log(this.list)
        console.log(data.data);
        this.loading = false // 此时数据已经push到数组中，把loading关闭 设为false
        if(results.length) {
          this.timesTamp = data.data.pre_timestamp
        } else {
          this.finished = true // 若数据全部加载完毕 则执行这里的代码
        }
      } catch (err) {
        console.log(err);
        this.error = true // 展示错误提示
        this.loading = false
      }
     
    },

    // 下拉刷新
   async onRefresh() {
      try {
        const {data} = await getPushArticles({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        console.log(data);
        const { results } = data.data
        this.list.unshift(...results)
        this.dropDownRefresh = `刷新成功，更新${results.length}条数据`
        this.refreshing = false
      } catch(err) {
        console.log(err);
        this.dropDownRefresh = '刷新失败'
      }
    },

    // 获取主页推荐文章的数据
   async PushArticles() {
     
    }
  },
}
</script>

<style lang="scss" scoped>
 .user-articles {
  height: 86vh;
  overflow: auto;
 }
</style>